using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;

namespace Framework.Library.Core.Utils.Web.UI.Controls
{
    public class Container<TOwner> : WebControl where TOwner : WebControl
    {
        private Dictionary<string, Control> _cachedFindControls;
        private TOwner _owner;
        private bool _renderDesignerRegion;

        public Container(TOwner owner)
        {
            _owner = owner;
        }

        private Dictionary<string, Control> CachedFindControls
        {
            get
            {
                if (_cachedFindControls == null)
                    _cachedFindControls = new Dictionary<string, Control>();

                return _cachedFindControls;
            }
        }

        public bool RenderDesignerRegion
        {
            get { return _renderDesignerRegion; }
            set { _renderDesignerRegion = value; }
        }

        private T FindControl<T>(string id, bool required, string errorMessage) where T : Control
        {
            Control control;
            T foundControl;

            if (!CachedFindControls.TryGetValue(id, out control))
            {
                // control wasn't cached. try to find it
                foundControl = FindControl(id) as T;

                // add to cache if found
                // otherwise throw an exception if required
                if (foundControl != null)
                    CachedFindControls.Add(id, foundControl);
                else if (required)
                    throw new Exception(errorMessage);
            }
            else
            {
                foundControl = (T) control;
            }

            return foundControl;
        }

        protected T FindOptionalControl<T>(string id) where T : Control
        {
            return FindControl<T>(id, false, null);
        }

        protected T FindRequiredControl<T>(string id, string errorMessage) where T : Control
        {
            return FindControl<T>(id, true, errorMessage);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (_renderDesignerRegion)
            {
                var table = new Table();
                var cell = new TableCell();

                table.Rows.Add(new TableRow());
                table.Rows[0].Cells.Add(cell);
                table.BorderWidth = new Unit(0, UnitType.Pixel);
                table.CellPadding = 0;
                table.CellSpacing = 0;

                cell.Attributes[DesignerRegion.DesignerRegionAttributeName] = "0";

                table.RenderControl(writer);
            }
            else
            {
                RenderContents(writer);
            }
        }
    }
}